﻿
// Our default grid options
var defaultGridOptions = {
    enableCellNavigation: true,
    enableColumnReorder: false,
    enableAddRow: false,
    editable: true,
    editOnDoubleClick: true,
    multiSelect: false,
    forceFitColumns: false,
    autoHeight: false,
    resizable: false,
    autoEdit: false,
    showHeaderRow: true,
    rowHeight: 36,
    headerHeight: 36,
    headerRowHeight: 36

};

$().ready(function () {
  //  $.metadata.setType("attr", "validate");
    $('.button').button();
    $('form').submit(function (event) {
        event.preventDefault();
    });
    var testsGrid = setUpTestsGrid($('#testsGrid'));
    var studyGrid = setUpStudyMaterialsGrid($('#studyMaterialsGrid'));
});

// Sets up the sample grid
function setUpTestsGrid($gridSelector) {
    var columns = [
        { id: "Name", name: "Name", field: "Name", width: 300, sortable: true },
        //{ id: "Score", name: "Score", field: "Score", width: 100, sortable: true },
        { id: "buttons", name: "", field: "", width: 190, sortable: false, formatter: CellButtonFormatter, buttons: ["Take Test"] }
    ];

    // Set some additional options
    var options = $.extend(true, {}, defaultGridOptions);
    options.hasHeaderFilters = true;

    // Create the grid
    var grid = new Slick.Grid($gridSelector, [], columns, options);
    grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));

    grid.updateHeaderRow();

    // Make the grid buttons use jQuery UI
    grid.onRender.subscribe(function (e, args) {
        $($gridSelector.selector + ' .slick-cell-button').button();
    });
    block({ element: $gridSelector, text: 'Loading' });
    $.getJSON('/Testing/ListTests', function (response) {
        if (response.Result)
            grid.dataView.setItems(response.Data);
        else {
            alert(response.Data);
        }
    });
    unblock({ element: $gridSelector });

    setUpTakeTestDialog();
    // setUpResultsDialog($gridSelector, grid);
    // Return the grid object so we can store it in a variable
    return grid;

    function setUpTakeTestDialog() {
        var $dialog = $('#takeTestDialog');
        var testValidator;

        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 600,
            height: 600,
            buttons:
                {
                    OK: function () {
                        if (!testValidator.form()) {
                            alert("You must fill out all questions in order to submit the test!");
                            return;
                        }
                        var row = grid.getDataItem(grid.getActiveCell().row);
                        // Submit test
                        block({ element: $dialog, text: 'Saving' });
                        $.post('/Testing/SubmitTest', {
                            testId: row.Id,
                            Answers: JSON.stringify(getAnswers())
                        }, function (response) {
                            if (response.Result) {
                                grid.dataView.deleteItem(row.Id);
                                grid.invalidate();
                                $dialog.dialog('close');
                            } else {
                                alert("Unable to submit your test: " + response.Data);
                            }
                        }).error(function () {
                            alert("Unable to submit your test. Please try again.");
                        }).complete(function () {
                            unblock({ element: $dialog });
                        });

                        function getAnswers() {
                            var answers = [];
                            $('#questionsAndAnswers input:checked').each(function () {
                                answers.push({ QuestionId: this.name, AnswerId: this.value });
                            });
                            return answers;
                        }

                        // Close the dialog
                        $(this).dialog('close');
                    }
                }
        });
        $(document).on('click', $gridSelector.selector + ' .slick-cell-button-Take_Test', function () {
            $('#questionsAndAnswers').empty();
            var row = grid.getDataItem(grid.getActiveCell().row);
            $dialog.dialog('option', { title: row.Name });
            $dialog.dialog('open');

            block({ element: $dialog, text: 'Loading' });
            $.getJSON('/Testing/TakeTest/' + row.Id,
                    function (response) {
                        if (response.Result) {
                            var $form = $('<form id="takeTestForm" method="get" action=""></form>');
                            $.each(response.Data, function () {
                                var question = this;
                                var $questionDiv = $(jQuery.validator.format('<div class="questionContainer"><div class="question">{0}. {1}</div></div>', question.Number, question.Text));
                                var $answersList = $('<ol class="answer"></ol>');
                                $.each(question.Answers, function () {
                                    var answer = this;
                                    var $answerHtml =
                                        $(jQuery.validator.format('<li><input type="radio" name="{0}" id="question_{1}_{2}" value="{3}" class="required"  validate="required:true" /><label for="question_{1}_{2}">{4}</label></li>',
                                        question.Id, question.Number, answer.Number, answer.Id, answer.Text));
                                    $answersList.append($answerHtml);
                                });
                                $questionDiv.append($answersList);
                                $form.append($questionDiv);
                            });
                            $form.appendTo($('#questionsAndAnswers'));
                            testValidator = $('#takeTestForm').validate({showErrors:function (){}});
                        } else {
                            alert(response.Data);
                            $dialog.dialog('close');
                        }
                    });
            unblock({ element: $dialog });
        });
    }
    //#region Results
    function setUpResultsDialog($testsGridSelector, testsGrid) {
        var $dialog = $('#testResultsDialog');
        var $gridSelector = $('#testResultsGrid');
        var columns = [
            { id: "Employee", name: "Employee", field: "Employee", width: 200, sortable: true },
            { id: "Score", name: "Score", field: "Score", width: 100, sortable: true },
            { id: "buttons", name: "", field: "", width: 200, sortable: false, formatter: CellButtonFormatter, buttons: ["Pass", "Results"] }
        ];

        // Set some additional options
        var options = $.extend(true, {}, defaultGridOptions);
        options.hasHeaderFilters = true;

        // Create the grid
        var grid = new Slick.Grid($gridSelector, [], columns, options);
        grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));

        grid.updateHeaderRow();

        // Make the grid buttons use jQuery UI
        grid.onRender.subscribe(function (e, args) {
            $('.slick-cell-button').button();
        });

        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 600,
            height: 600,
            buttons:
                {
                    OK: function () {
                        grid.dataView.setItems({});
                        // Close the dialog
                        $(this).dialog('close');
                    }
                }
        });

        setUpEmployeeResultsDialog($gridSelector, grid);

        $(document).on('click', $testsGridSelector.selector + ' .slick-cell-button-Results', function () {
            $dialog.dialog('open');
            var row = testsGrid.getDataItem(testsGrid.getActiveCell().row);

            $('#testResults_name').text(row.Name);
            block({ element: $gridSelector, text: 'Loading' });
            $.getJSON('/TestManagement/TakeTest/' + testsGrid.getDataItem(testsGrid.getActiveCell().row).Id,
            function (response) {
                if (response.Result) {
                    grid.dataView.setItems(response.Data);
                    grid.dataView.refresh();
                } else {
                    alert(response.Data);
                }
            });
            unblock({ element: $gridSelector });
        });
        // Return the grid object so we can store it in a variable
        return grid;

        //#region Functions
        function setUpEmployeeResultsDialog($resultsGridSelector, resultsGrid) {
            var $dialog = $('#employeeResultsDialog');
            $dialog.dialog({
                modal: true,
                resizable: false,
                autoOpen: false,
                width: 600,
                height: 600,
                buttons:
                {
                    OK: function () {
                        // Close the dialog
                        $(this).dialog('close');
                    }
                }
            });
            $(document).on('click', $resultsGridSelector.selector + ' .slick-cell-button-Results', function () {
                $dialog.dialog('open');

                block({ element: $gridSelector, text: 'Loading' });
                $.getJSON('/TestManagement/ListEmployeeResults',
                    {
                        testId: testsGrid.getDataItem(testsGrid.getActiveCell().row).Id,
                        employeeId: resultsGrid.getDataItem(resultsGrid.getActiveCell().row).Id
                    },
                    function (response) {
                        if (response.Result) {
                            $.each(response.Data, function () {
                                var question = this;
                                var $questionDiv = $(jQuery.validator.format('<div><div class="question">{0}. {1}</div></div>', question.Number, question.Text));
                                var $answersList = $('<ol class="answer"></ol>');
                                $.each(question.Answers, function () {
                                    var answer = this;
                                    var $answerHtml = $(jQuery.validator.format('<li>{0}</li>', answer.Text));
                                    if (answer.Id == question.EmployeeAnswerId && answer.Id != question.CorrectAnswerId)
                                        $answerHtml.addClass('wrongAnswer');
                                    if (answer.Id == question.CorrectAnswerId)
                                        $answerHtml.addClass('rightAnswer');
                                    $answersList.append($answerHtml);
                                });
                                $questionDiv.append($answersList);
                                $('#questionsAndAnswers').append($questionDiv);
                            });
                        } else {
                            alert(response.Data);
                            $dialog.dialog('close');
                        }
                    });
                unblock({ element: $gridSelector });
            });
        }
        //#endregion
    }
    //#endregion

}

// Sets up the sample grid
function setUpStudyMaterialsGrid($gridSelector) {
    var columns = [
        { id: "Name", name: "Name", field: "Name", width: 300, sortable: true },
        { id: "buttons", name: "", field: "", width: 190, sortable: false, formatter: CellButtonFormatter, buttons: ["View"] }
    ];

    // Set some additional options
    var options = $.extend(true, {}, defaultGridOptions);
    options.hasHeaderFilters = true;

    // Create the grid
    var grid = new Slick.Grid($gridSelector, [], columns, options);
    grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));

    grid.updateHeaderRow();

    // Make the grid buttons use jQuery UI
    grid.onRender.subscribe(function (e, args) {
        $($gridSelector.selector + ' .slick-cell-button').button();
    });
    block({ element: $gridSelector, text: 'Loading' });
    $.getJSON('/StudyMaterialsManagement/ListMaterials', function (response) {
        if (response.Result)
            grid.dataView.setItems(response.Data);
        else {
            alert(response.Data);
        }
    });
    unblock({ element: $gridSelector });
    
    $(document).on('click', $gridSelector.selector + ' .slick-cell-button-View', function () {
        var data = grid.getDataItem(grid.getActiveCell().row);
        window.open('/StudyMaterialsManagement/View/' + data.Id, data.Name);
    });
    // setUpResultsDialog($gridSelector, grid);
    // Return the grid object so we can store it in a variable
    return grid;

    //#region Results
    function setUpResultsDialog($testsGridSelector, testsGrid) {
        var $dialog = $('#testResultsDialog');
        var $gridSelector = $('#testResultsGrid');
        var columns = [
            { id: "Employee", name: "Employee", field: "Employee", width: 200, sortable: true },
            { id: "Score", name: "Score", field: "Score", width: 100, sortable: true },
            { id: "buttons", name: "", field: "", width: 200, sortable: false, formatter: CellButtonFormatter, buttons: ["Pass", "Results"] }
        ];

        // Set some additional options
        var options = $.extend(true, {}, defaultGridOptions);
        options.hasHeaderFilters = true;

        // Create the grid
        var grid = new Slick.Grid($gridSelector, [], columns, options);
        grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));

        grid.updateHeaderRow();

        // Make the grid buttons use jQuery UI
        grid.onRender.subscribe(function (e, args) {
            $('.slick-cell-button').button();
        });

        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 600,
            height: 600,
            buttons:
                {
                    OK: function () {
                        grid.dataView.setItems({});
                        // Close the dialog
                        $(this).dialog('close');
                    }
                }
        });

        setUpEmployeeResultsDialog($gridSelector, grid);

        $(document).on('click', $testsGridSelector.selector + ' .slick-cell-button-Results', function () {
            $dialog.dialog('open');
            var row = testsGrid.getDataItem(testsGrid.getActiveCell().row);

            $('#testResults_name').text(row.Name);
            block({ element: $gridSelector, text: 'Loading' });
            $.getJSON('/TestManagement/TakeTest/' + testsGrid.getDataItem(testsGrid.getActiveCell().row).Id,
            function (response) {
                if (response.Result) {
                    grid.dataView.setItems(response.Data);
                    grid.dataView.refresh();
                } else {
                    alert(response.Data);
                }
            });
            unblock({ element: $gridSelector });
        });
        // Return the grid object so we can store it in a variable
        return grid;

        //#region Functions
        function setUpEmployeeResultsDialog($resultsGridSelector, resultsGrid) {
            var $dialog = $('#employeeResultsDialog');
            $dialog.dialog({
                modal: true,
                resizable: false,
                autoOpen: false,
                width: 600,
                height: 600,
                buttons:
                {
                    OK: function () {
                        // Close the dialog
                        $(this).dialog('close');
                    }
                }
            });
            $(document).on('click', $resultsGridSelector.selector + ' .slick-cell-button-Results', function () {
                $dialog.dialog('open');

                block({ element: $gridSelector, text: 'Loading' });
                $.getJSON('/TestManagement/ListEmployeeResults',
                    {
                        testId: testsGrid.getDataItem(testsGrid.getActiveCell().row).Id,
                        employeeId: resultsGrid.getDataItem(resultsGrid.getActiveCell().row).Id
                    },
                    function (response) {
                        if (response.Result) {
                            $.each(response.Data, function () {
                                var question = this;
                                var $questionDiv = $(jQuery.validator.format('<div><div class="question">{0}. {1}</div></div>', question.Number, question.Text));
                                var $answersList = $('<ol class="answer"></ol>');
                                $.each(question.Answers, function () {
                                    var answer = this;
                                    var $answerHtml = $(jQuery.validator.format('<li>{0}</li>', answer.Text));
                                    if (answer.Id == question.EmployeeAnswerId && answer.Id != question.CorrectAnswerId)
                                        $answerHtml.addClass('wrongAnswer');
                                    if (answer.Id == question.CorrectAnswerId)
                                        $answerHtml.addClass('rightAnswer');
                                    $answersList.append($answerHtml);
                                });
                                $questionDiv.append($answersList);
                                $('#questionsAndAnswers').append($questionDiv);
                            });
                        } else {
                            alert(response.Data);
                            $dialog.dialog('close');
                        }
                    });
                unblock({ element: $gridSelector });
            });
        }
        //#endregion
    }
    //#endregion

}